package com.iamteer.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.iamteer.dao.IAdminDao;
import com.iamteer.entity.Admin;

/**
 * 2. 数据访问层接口的实现类
 * （引入 DbUtils 组件简化 jdbc 操作）
 * @author Chuck
 *
 */
public class AdminDao implements IAdminDao {
	
	private Connection con;
	private QueryRunner qr = new QueryRunner();
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";

	@Override
	public void save(Admin admin) {
		String sql = "INSERT INTO admin(userName,password) VALUES(?,?)";
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			qr.update(con, sql, admin.getUsername(), admin.getPassword());
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}		
	}

	@Override
	public Admin findByNameAndPwd(Admin admin) {
		String sql = "SELECT * FROM admin WHERE userName=? AND password=?";
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			Admin ad = qr.query(con, sql, 
					new BeanHandler<Admin>(Admin.class), 
					admin.getUsername(), 
					admin.getPassword());
			return ad;
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public boolean userExists(String name) {
		String sql = "SELECT 1 FROM admin WHERE userName=?";
		try {
			//1 连接数据库
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			Long in = qr.query(con, sql, new ScalarHandler<Long>(), name);
			if (in != null) {
				return true;
			}
			return false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}		
	}
}
